package com.emotion.sshticket.interceptors;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.emotion.sshticket.vo.AdminUserVO;

public class AdminInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(
			HttpServletRequest request, HttpServletResponse response,
			Object handler) throws Exception {
		AdminUserVO adminUserVO = null;
		String url = request.getRequestURI();
		HttpSession session = request.getSession(false);
		if (session != null) {
			adminUserVO = (AdminUserVO) session.getAttribute("adminUser");
		}

		if (getSessionCheckURL(request)) {
			if (adminUserVO == null) {
				//String returnUrl = url;
				String returnUrl = url.replaceAll("/", "");

				request.setAttribute("returnUrl", returnUrl);
				RequestDispatcher rd = request.getRequestDispatcher("/admin/loginForm.do");
				rd.forward(request, response);
				return false;
			}
		}
		return super.preHandle(request, response, handler);
	}


	private boolean getSessionCheckURL(HttpServletRequest request) {
		boolean sessionCheckURL = true;
		String url = request.getRequestURI();
		url = url.replaceAll(".do", "");
		if (url.equals("/admin/loginForm")) {
			sessionCheckURL = false;
		} else if (url.equals("/admin/login")) {
			sessionCheckURL = false;
		} else {
			sessionCheckURL = true;
		}

		return sessionCheckURL;
	}

}
